package com.flink.job;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WordCount {

    public static void main(String[] args) throws Exception {
        //{@link DataSet} 批处理 api, 处理离线数据
        //* @author regotto
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSource<String> dataSource = env.readTextFile("/bigdata/hello.txt");
        // 将单词按照空格分割, 变为 (word, 1) 形式的二元组
        DataSet<Tuple2<String, Integer>> resultSet = dataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split("\\W+");
                for (String s : words) {
                    out.collect(new Tuple2<String, Integer>(s, 1));
                }
            }
            // 按照 tuple2 index = 0 进行分组, 按照 index = 1 进行求和
        }).groupBy(0).sum(1);
        resultSet.print();
        System.out.println("结果集为--："+resultSet.toString());
    }

}
